// API服务封装
class APIService {
  constructor() {
    this.baseURL = '/api' // 假设API基础路径为/api
    this.token = localStorage.getItem('admin_token') || ''
  }
  
  // 设置认证token
  setToken(token) {
    this.token = token
    localStorage.setItem('admin_token', token)
  }
  
  // 清除认证token
  clearToken() {
    this.token = ''
    localStorage.removeItem('admin_token')
  }
  
  // 通用请求方法
  async request(url, options = {}) {
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers
    }
    
    if (this.token) {
      headers['Authorization'] = `Bearer ${this.token}`
    }
    
    const config = {
      ...options,
      headers
    }
    
    // 对于FormData请求，删除Content-Type头，让浏览器自动设置
    if (options.body instanceof FormData) {
      delete headers['Content-Type']
    }
    
    try {
      const response = await fetch(this.baseURL + url, config)
      
      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.message || '请求失败')
      }
      
      return await response.json()
    } catch (error) {
      console.error('API请求失败:', error)
      throw error
    }
  }
  
  // 用户相关API
  user = {
    // 获取用户列表
    getUsers: (params) => {
      const query = new URLSearchParams(params).toString()
      return this.request(`/users?${query}`)
    },
    
    // 创建用户
    createUser: (userData) => {
      return this.request('/users', {
        method: 'POST',
        body: JSON.stringify(userData)
      })
    },
    
    // 更新用户
    updateUser: (id, userData) => {
      return this.request(`/users/${id}`, {
        method: 'PUT',
        body: JSON.stringify(userData)
      })
    },
    
    // 删除用户
    deleteUser: (id) => {
      return this.request(`/users/${id}`, {
        method: 'DELETE'
      })
    }
  }
  
  // 文章相关API
  article = {
    // 获取文章列表
    getArticles: (params) => {
      const query = new URLSearchParams(params).toString()
      return this.request(`/articles?${query}`)
    },
    
    // 创建文章
    createArticle: (articleData) => {
      return this.request('/articles', {
        method: 'POST',
        body: JSON.stringify(articleData)
      })
    },
    
    // 更新文章
    updateArticle: (id, articleData) => {
      return this.request(`/articles/${id}`, {
        method: 'PUT',
        body: JSON.stringify(articleData)
      })
    },
    
    // 删除文章
    deleteArticle: (id) => {
      return this.request(`/articles/${id}`, {
        method: 'DELETE'
      })
    },
    
    // 获取分类列表
    getCategories: () => {
      return this.request('/categories')
    }
  }
  
  // 分类相关API
  category = {
    // 获取分类列表
    getCategories: (params) => {
      const query = new URLSearchParams(params).toString()
      return this.request(`/categories?${query}`)
    },
    
    // 创建分类
    createCategory: (categoryData) => {
      return this.request('/categories', {
        method: 'POST',
        body: JSON.stringify(categoryData)
      })
    },
    
    // 更新分类
    updateCategory: (id, categoryData) => {
      return this.request(`/categories/${id}`, {
        method: 'PUT',
        body: JSON.stringify(categoryData)
      })
    },
    
    // 删除分类
    deleteCategory: (id) => {
      return this.request(`/categories/${id}`, {
        method: 'DELETE'
      })
    }
  }
  
  // 标签相关API
  tag = {
    // 获取标签列表
    getTags: (params) => {
      const query = new URLSearchParams(params).toString()
      return this.request(`/tags?${query}`)
    },
    
    // 创建标签
    createTag: (tagData) => {
      return this.request('/tags', {
        method: 'POST',
        body: JSON.stringify(tagData)
      })
    },
    
    // 更新标签
    updateTag: (id, tagData) => {
      return this.request(`/tags/${id}`, {
        method: 'PUT',
        body: JSON.stringify(tagData)
      })
    },
    
    // 删除标签
    deleteTag: (id) => {
      return this.request(`/tags/${id}`, {
        method: 'DELETE'
      })
    }
  }
  
  // 评论相关API
  comment = {
    // 获取评论列表
    getComments: (params) => {
      const query = new URLSearchParams(params).toString()
      return this.request(`/comments?${query}`)
    },
    
    // 更新评论
    updateComment: (id, commentData) => {
      return this.request(`/comments/${id}`, {
        method: 'PUT',
        body: JSON.stringify(commentData)
      })
    },
    
    // 删除评论
    deleteComment: (id) => {
      return this.request(`/comments/${id}`, {
        method: 'DELETE'
      })
    }
  }
  
  // 媒体相关API
  media = {
    // 获取媒体文件列表
    getMedia: (params) => {
      const query = new URLSearchParams(params).toString()
      return this.request(`/media?${query}`)
    },
    
    // 上传媒体文件
    uploadMedia: (formData) => {
      return this.request('/media/upload', {
        method: 'POST',
        body: formData
      })
    },
    
    // 删除媒体文件
    deleteMedia: (id) => {
      return this.request(`/media/${id}`, {
        method: 'DELETE'
      })
    },
    
    // 批量删除媒体文件
    deleteMultipleMedia: (ids) => {
      return this.request('/media/batch-delete', {
        method: 'POST',
        body: JSON.stringify({ ids })
      })
    }
  }
  
  // 设置相关API
  settings = {
    // 获取系统设置
    getSettings: () => {
      return this.request('/settings')
    },
    
    // 更新系统设置
    updateSettings: (settingsData) => {
      return this.request('/settings', {
        method: 'PUT',
        body: JSON.stringify(settingsData)
      })
    },
    
    // 上传Logo
    uploadLogo: (formData) => {
      return this.request('/settings/upload-logo', {
        method: 'POST',
        body: formData
      })
    }
  }
  
  // 认证相关API
  auth = {
    // 管理员登录
    login: (credentials) => {
      return this.request('/admin/login', {
        method: 'POST',
        body: JSON.stringify(credentials)
      })
    },
    
    // 获取当前用户信息
    getCurrentUser: () => {
      return this.request('/admin/profile')
    },
    
    // 登出
    logout: () => {
      return this.request('/admin/logout', {
        method: 'POST'
      })
    }
  }
}

// 创建API服务实例
const apiService = new APIService()

export default apiService